package com.zyp.app;

import com.zyp.dao.AccountDao;
import com.zyp.dao.TransactionDao;
import com.zyp.entity.Account;
import com.zyp.entity.Transaction;
import com.zyp.utils.DruidUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Scanner;

public class Topic1Test {

    private Transaction transaction = new Transaction();

    @Test
    public void TransferTest() {

        System.out.println("转账操作");
//        Scanner scanner = new Scanner(System.in);

//        System.out.println("请输入转出卡号：");
//        transaction.setCardid(scanner.next());
        transaction.setCardid("1122334455");

//        System.out.println("请选择交易类型：转入/转出");
//        transaction.setTratype(scanner.next());
        transaction.setTratype("转出");

//        System.out.println("请输入要交易的金额：");
//        transaction.setTramoney(scanner.nextDouble());
        transaction.setTramoney(5000);


        AccountDao accountDao = new AccountDao();
        TransactionDao transactionDao = new TransactionDao();
        Account account = null;
        Connection connection = null;
        try {
            account = accountDao.judgmentAmount(transaction);
            connection = DruidUtils.getConnection();
            connection.setAutoCommit(false);

            if (account != null) {
                accountDao.updateTransferIn(transaction);//转出操作
                transactionDao.add(transaction);//插入记录

                //转入
                transaction.setTratype("转入");
//            System.out.println("请输入转入对象卡号：");
//            transaction.setCardid(scanner.next());//输入要转入的对象
                transaction.setCardid("55443332211");

                accountDao.updateTransferOut(transaction);//转入操作
                transactionDao.add(transaction);//插入记录
                connection.commit(); //提交事务
                System.out.println("转账成功");
            } else {
                System.out.println("余额不足！");
            }
        } catch (SQLException e) {
            try {
                connection.rollback();//出现问题，事务回滚
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        } finally {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
}
